/**
 * 服务引导程序
 * 应用启动时的统一初始化入口
 */

import { registerServices, healthCheck, gracefulShutdown } from '../di/ServiceRegistry';
import { globalCache } from '../cache/SimpleCache';

/**
 * 引导配置选项
 */
export interface BootstrapOptions {
    /** 是否启用开发模式 */
    enableDevMode?: boolean;
    /** 是否启用健康检查 */
    enableHealthCheck?: boolean;
    /** 是否启用优雅关闭 */
    enableGracefulShutdown?: boolean;
    /** 自定义初始化函数 */
    customInitializers?: Array<() => Promise<void> | void>;
    /** 健康检查间隔（毫秒） */
    healthCheckInterval?: number;
}

/**
 * 应用状态
 */
export enum AppState {
    INITIALIZING = 'initializing',
    RUNNING = 'running',
    STOPPING = 'stopping',
    STOPPED = 'stopped',
    ERROR = 'error'
}

/**
 * 服务引导程序类
 */
export class ServiceBootstrap {
    private static instance: ServiceBootstrap;
    private appState: AppState = AppState.INITIALIZING;
    private healthCheckTimer?: NodeJS.Timeout;
    private shutdownHandlers: Array<() => Promise<void>> = [];

    private constructor() {}

    /**
     * 获取单例实例
     */
    static getInstance(): ServiceBootstrap {
        if (!ServiceBootstrap.instance) {
            ServiceBootstrap.instance = new ServiceBootstrap();
        }
        return ServiceBootstrap.instance;
    }

    /**
     * 初始化应用
     */
    async initialize(options: BootstrapOptions = {}): Promise<void> {
        console.log('🚀 开始初始化应用...');
        
        try {
            this.appState = AppState.INITIALIZING;
            
            // 1. 注册所有服务
            console.log('📦 注册服务...');
            registerServices();
            
            // 2. 执行自定义初始化器
            if (options.customInitializers) {
                console.log('🔧 执行自定义初始化器...');
                for (const initializer of options.customInitializers) {
                    await initializer();
                }
            }
            
            // 3. 健康检查
            if (options.enableHealthCheck !== false) {
                console.log('🏥 执行健康检查...');
                const healthResult = await healthCheck();
                if (!healthResult.success) {
                    console.warn('⚠️ 健康检查发现问题:', healthResult.issues);
                } else {
                    console.log('✅ 健康检查通过');
                }
                
                // 启动定期健康检查
                if (options.healthCheckInterval) {
                    this.startPeriodicHealthCheck(options.healthCheckInterval);
                }
            }
            
            // 4. 设置优雅关闭
            if (options.enableGracefulShutdown !== false) {
                this.setupGracefulShutdown();
            }
            
            // 5. 开发模式配置
            if (options.enableDevMode) {
                this.setupDevMode();
            }
            
            this.appState = AppState.RUNNING;
            console.log('🎉 应用初始化完成！');
            
        } catch (error) {
            this.appState = AppState.ERROR;
            console.error('❌ 应用初始化失败:', error);
            throw error;
        }
    }

    /**
     * 启动定期健康检查
     */
    private startPeriodicHealthCheck(interval: number): void {
        this.healthCheckTimer = setInterval(async () => {
            try {
                const result = await healthCheck();
                if (!result.success) {
                    console.warn('⚠️ 定期健康检查发现问题:', result.issues);
                }
            } catch (error) {
                console.error('❌ 健康检查执行失败:', error);
            }
        }, interval);
        
        console.log(`⏰ 已启动定期健康检查，间隔 ${interval}ms`);
    }

    /**
     * 设置优雅关闭
     */
    private setupGracefulShutdown(): void {
        const shutdown = async (signal: string) => {
            console.log(`📴 收到 ${signal} 信号，开始优雅关闭...`);
            await this.shutdown();
            process.exit(0);
        };

        process.on('SIGTERM', () => shutdown('SIGTERM'));
        process.on('SIGINT', () => shutdown('SIGINT'));
        
        // Windows 平台的处理
        if (process.platform === 'win32') {
            const rl = require('readline').createInterface({
                input: process.stdin,
                output: process.stdout
            });
            
            rl.on('SIGINT', () => shutdown('SIGINT'));
        }
        
        console.log('🛡️ 已设置优雅关闭处理');
    }

    /**
     * 设置开发模式
     */
    private setupDevMode(): void {
        console.log('🔧 启用开发模式');
        
        // 暴露全局调试对象
        (global as any).AppBootstrap = this;
        (global as any).AppCache = globalCache;
        
        // 启用详细日志
        process.env.DEBUG = 'true';
        
        // 未处理异常捕获
        process.on('unhandledRejection', (reason, promise) => {
            console.error('🚨 未处理的Promise拒绝:', reason);
            console.error('Promise:', promise);
        });
        
        process.on('uncaughtException', (error) => {
            console.error('🚨 未捕获的异常:', error);
        });
    }

    /**
     * 添加关闭处理器
     */
    addShutdownHandler(handler: () => Promise<void>): void {
        this.shutdownHandlers.push(handler);
    }

    /**
     * 优雅关闭
     */
    async shutdown(): Promise<void> {
        if (this.appState === AppState.STOPPING || this.appState === AppState.STOPPED) {
            return;
        }
        
        this.appState = AppState.STOPPING;
        console.log('🔄 开始关闭应用...');
        
        try {
            // 停止健康检查
            if (this.healthCheckTimer) {
                clearInterval(this.healthCheckTimer);
                this.healthCheckTimer = undefined;
            }
            
            // 执行自定义关闭处理器
            for (const handler of this.shutdownHandlers) {
                try {
                    await handler();
                } catch (error) {
                    console.error('❌ 关闭处理器执行失败:', error);
                }
            }
            
            // 关闭服务
            await gracefulShutdown();
            
            this.appState = AppState.STOPPED;
            console.log('✅ 应用已优雅关闭');
            
        } catch (error) {
            console.error('❌ 应用关闭时发生错误:', error);
            this.appState = AppState.ERROR;
        }
    }

    /**
     * 获取应用状态
     */
    getAppState(): AppState {
        return this.appState;
    }

    /**
     * 检查应用是否正在运行
     */
    isRunning(): boolean {
        return this.appState === AppState.RUNNING;
    }

    /**
     * 重启应用（开发模式）
     */
    async restart(options?: BootstrapOptions): Promise<void> {
        if (process.env.NODE_ENV !== 'development') {
            throw new Error('重启功能仅在开发环境可用');
        }
        
        console.log('🔄 重启应用...');
        await this.shutdown();
        await this.initialize(options);
    }

    /**
     * 获取应用统计信息
     */
    getStats(): {
        state: AppState;
        uptime: number;
        memoryUsage: NodeJS.MemoryUsage;
        cacheStats: any;
    } {
        return {
            state: this.appState,
            uptime: process.uptime(),
            memoryUsage: process.memoryUsage(),
            cacheStats: globalCache.getStats()
        };
    }
}

/**
 * 便捷的初始化函数
 */
export async function bootstrapApp(options: BootstrapOptions = {}): Promise<ServiceBootstrap> {
    const bootstrap = ServiceBootstrap.getInstance();
    await bootstrap.initialize(options);
    return bootstrap;
}

/**
 * 快速启动（带默认配置）
 */
export async function quickStart(): Promise<ServiceBootstrap> {
    return bootstrapApp({
        enableDevMode: process.env.NODE_ENV === 'development',
        enableHealthCheck: true,
        enableGracefulShutdown: true,
        healthCheckInterval: 5 * 60 * 1000 // 5分钟
    });
}

/**
 * 生产环境启动
 */
export async function productionStart(customInitializers?: Array<() => Promise<void> | void>): Promise<ServiceBootstrap> {
    return bootstrapApp({
        enableDevMode: false,
        enableHealthCheck: true,
        enableGracefulShutdown: true,
        customInitializers,
        healthCheckInterval: 10 * 60 * 1000 // 10分钟
    });
}

/**
 * 开发环境启动
 */
export async function developmentStart(): Promise<ServiceBootstrap> {
    return bootstrapApp({
        enableDevMode: true,
        enableHealthCheck: true,
        enableGracefulShutdown: true,
        healthCheckInterval: 2 * 60 * 1000 // 2分钟
    });
}
